<template>
  <div class="drawer-content">
    <filter-input
      v-model="paramsObj"
      :filter-list="filterList"
      show-search-btn
      line-feed
      @handelClick="queryClick"
      @queryEmpty="queryEmpty"
    />
    <el-tabs v-model="curTabName" type="card" class="contract-detail-tabs-container" style="margin: 8px 0px" @tab-click="onSubActiveOrderChange">
      <el-tab-pane label="可见合同" name="all"/>
      <el-tab-pane name="other">
        <div slot="label">
          <span>不可见合同</span>
          <el-tooltip :open-delay="800" placement="top" effect="dark">
            <div slot="content" style="max-width: 210px">可通过创建人、审批人操作抄送后可见</div>
            <tipIcon is-diy style="position:relative;top:2px;"/>
          </el-tooltip>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div class="table-list">
      <div v-loading="listLoading">
        <template v-if="(isAllTab && list.items.length > 0) || (isOtherTab && otherList.length)">
          <u-table
            ref="legalTableRef"
            :data="isAllTab?list.items:(otherList)"
            :row-class-name="(data) => tableRowClassName(data)"
            :border="true"
            :max-height="'600px'"
            class="fb-table"
            beautify-table
            header-drag-style
            header-cell-class-name="order-data-header-cell"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            fit
            select-callback
            hightlight-current-rowref="tableRef"
            @sort-change="sortMethod">
            <u-table-column align="left" label="项目名称" min-width="150">
              <template slot-scope="scope">
                <el-tooltip v-if="isAllTab" :open-delay="800" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.contractName || '--' }}</div>
                  <div class="ellipsisOne" style="cursor:pointer;color:#406eff;" @click="toDetail(scope.row)">{{ scope.row.contractName || '--' }}</div>
                </el-tooltip>
                <ToolTip v-else :content="getColumnName(scope.row.contractName, scope.row.projectName)" />
              </template>
            </u-table-column>
            <u-table-column :sortable="isAllTab?'custom':false" align="left" label="合同编号" min-width="130" prop="contractCode">
              <template slot-scope="scope">
                <ToolTip :content="getColumnName(scope.row.contractCode, scope.row.contractNum)" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="合同类型" min-width="135">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.contractType || scope.row.contractType === 0 " :open-delay="800" class="ellipsisOne" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.contractType | contractType }}</div>
                  <div class="ellipsisOne">{{ scope.row.contractType | contractType }}</div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <template v-if="isAllTab">
              <u-table-column align="left" label="签约对方" min-width="120">
                <template slot-scope="scope">
                  <el-tooltip :open-delay="800" placement="top" effect="dark">
                    <div slot="content" style="max-width: 200px;">{{ scope.row.oppCompany || '--' }}</div>
                    <div class="ellipsisOne">{{ scope.row.oppCompany || '--' }}</div>
                  </el-tooltip>
                </template>
              </u-table-column>
              <u-table-column align="left" label="我方签约主体" min-width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.subjectName"/>
                </template>
              </u-table-column>
              <u-table-column align="left" label="合作方式" width="100">
                <template slot-scope="scope">
                  {{ scope.row.contractDate | mapOptions(options.dateTypeOptions) }}
                </template>
              </u-table-column>
              <u-table-column sortable="custom" align="left" label="合同日期" width="210" prop="contractEffectEndDate">
                <template slot-scope="scope">
                  <el-tooltip :open-delay="800" placement="top" effect="dark">
                    <div slot="content" style="max-width: 220px; white-space: nowrap; padding: 0 10px;">
                      <span v-if="scope.row.contractDate === 1 || scope.row.contractDate === null">{{ scope.row.contractEffectStartDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }} {{ handleLimit(scope.row) }} {{ scope.row.contractEffectEndDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                      <span v-else>{{ scope.row.pushTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                    </div>
                    <div class="ellipsisOne">
                      <span v-if="scope.row.contractDate === 1 || scope.row.contractDate === null">{{ scope.row.contractEffectStartDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }} {{ handleLimit(scope.row) }} {{ scope.row.contractEffectEndDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                      <span v-else>{{ scope.row.pushTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                    </div>
                  </el-tooltip>
                </template>
              </u-table-column>
              <u-table-column sortable="custom" align="left" label="审批进度" min-width="120" prop="lastAuditTime">
                <template slot-scope="scope">
                  {{ scope.row.reviewProgress || '--' }}
                </template>
              </u-table-column>
            </template>
            <u-table-column align="left" label="申请人" min-width="120">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.proposer" :label="scope.row.proposerName || scope.row.proposer" :user-id="scope.row.proposerId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请人部门" min-width="120">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.department || scope.row.proposerDepartmentName" :open-delay="800" placement="top" effect="dark">
                  <div slot="content" style="max-width: 200px;">{{ scope.row.proposerDepartmentName || scope.row.department || '--' }}</div>
                  <div class="ellipsisOne">{{ scope.row.proposerDepartmentName || scope.row.department || '--' }}</div>
                </el-tooltip>
                <span v-else>--</span>
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建人" min-width="120">
              <template slot-scope="scope">
                <CheckUserInfo v-if="scope.row.creator" :label="scope.row.creator" :user-id="scope.row.creatorId" />
                <div v-else>--</div>
              </template>
            </u-table-column>
          </u-table>
        </template>
        <div v-else style="margin-bottom: 24px;text-align: center;">
          <empty-placeholder :text="emptyText" :empty-img-top="'40px'"/>
          <span v-if="isAllTab">智能提示：切换至【不可见合同】可搜索无权限查看的合同噢~</span>
        </div>
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-if="isAllTab"
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[10, 50, 100, 250, 500]"
          :layout="pageLayout"
          :small="true"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
      <el-row v-if="isAllTab || isOtherTab" type="flex" justify="left">
        <div class="delete-button-container">
          <div v-if="isOtherTab" class="tip">搜索他人合同最多展示10条</div>
        </div>
        <el-pagination
          v-if="!showMobilePage && isAllTab"
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[10, 50, 100, 250, 500]"
          :layout="showMobilePage ? pageLayout : 'total, prev, pager, next, sizes, jumper'"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
    </div>
  </div>
</template>

<script>
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import FilterInput from '@/components/Tool/filter';
import { getList } from '@/api/legal';
import { getDepartmentAll } from '@/api/config';
import { getIssueOurTitleList } from '@/api/issueInvoice';
import { encryption } from '@/utils';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { standardFormatNoHour } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import { mapOptions } from '@/filters';
import { contractType } from '@/filters/status';
import options from '@/views/legal/module/options';
import axios from 'axios';
import { mapState } from 'vuex';
import mobileTable from '@/mixins/mobileTable';
import TableAdaptive from '@/mixins/tableAdaptive';
import tableSelections from '@/mixins/tableSelections';

export default {
  name: 'ContractTable',
  filters: {
    standardFormatNoHour,
    moneyFilter,
    contractType,
    mapOptions
  },
  components: {
    FilterInput,
    EmptyPlaceholder
  },
  mixins: [tableSelections, TableAdaptive, mobileTable],
  props: {
    oppCompanyId: { // 签约主体ID
      type: String | Number,
      default: ''
    },
    oppCompany: { // 签约主体
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      expandParams: { oppCompanyType: 3 },
      filterInput: {},
      otherFilterInput: {},
      page: 1,
      perPage: 10,
      list: {
        items: [],
        page: 1,
        perPage: 10,
        total: 0
      },
      sortType: '',
      sortName: '',
      listLoading: false,
      options,
      idKey: 'id', // 多选框参数
      isUmyTable: true,
      tableRefName: 'legalTableRef',
      curTabName: 'all',
      deptTreeList: [],
      otherList: [],
      rangeKeyArr: [
        { attr: 'contractEffectDate', start: 'contractEffectStartDate', end: 'contractEffectEndDate', type: 'round' },
        { attr: 'contractAmount', start: 'contractAmountMin', end: 'contractAmountMax', type: 'moneyFixedTwo' }
      ],
      cancelToken: null,
      subjectOptions: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isOtherTab() {
      return this.curTabName === 'other';
    },
    isAllTab() {
      return this.curTabName === 'all';
    },
    emptyText() {
      if (this.isAllTab) {
        return '找不到合同，请换个关键词搜索';
      } else if (this.isOtherTab) {
        return '搜索项目名称、合同编号等可查找他人合同';
      }
      return '暂无数据';
    },
    filterList() {
      const arr = [
        { keyword: 'contractCode', name: '合同编号', type: 'input', labelWidth: '99px' },
        { keyword: 'contractName', name: '项目名称', type: 'input', labelWidth: '99px' },
        { keyword: 'proposer', name: '申请人', type: 'input', labelWidth: '99px' },
        { keyword: 'creator', name: '创建人', type: 'input', labelWidth: '99px' },
        { keyword: 'departmentIdList', name: '申请人部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'contractType', name: '合同类型', type: 'select', options: [...options.typeOptions] },
        { keyword: 'contractAmount', name: '合同金额', labelWidth: '99px', type: 'inputRange', isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        { keyword: 'oppCompanyId', name: '签约对方Id', type: 'input', labelWidth: '99px' }
      ];
      if (!this.isOtherTab) {
        arr.push({ keyword: 'oppCompany', name: '签约对方', type: 'input', labelWidth: '99px' });
        arr.push({ keyword: 'contractSubject', name: '我方签约主体', type: 'select', options: this.subjectOptions, placeholder: '签约主体' });
        arr.push({ keyword: 'contractDate', name: '合作方式', type: 'select', options: [...options.dateTypeOptions] });
        arr.push({ keyword: 'contractEffectDate', name: '合同有效期', type: 'rangeDate', timeType: 'daterange', labelWidth: '99px' });
      }
      return arr;
    },
    paramsObj: {
      get() {
        if (this.isOtherTab) return this.otherFilterInput;
        return this.filterInput;
      },
      set(data) {
        if (this.isOtherTab) {
          this.otherFilterInput = data;
        } else {
          this.filterInput = data;
        }
      }
    }
  },
  created() {
    if (!this.oppCompanyId) {
      this.$set(this.paramsObj, 'oppCompany', this.oppCompany);
    } else {
      this.$set(this.paramsObj, 'oppCompanyId', this.oppCompanyId);
    }
    this.init();
  },
  methods: {
    getSubJectOptions() {
      this.subjectOptions = [];
      getIssueOurTitleList().then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.subjectOptions.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '所属公司'
            });
          });
        }
      });
    },
    // 申请部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    // 初始获取数据
    init(data) {
      this.curTabName = 'all';
      this.fetchData();
      this.queryDeptTreeList();
      this.getSubJectOptions();
    },
    getColumnName(name1, name2) {
      return name2 || name1;
    },
    handleLimit(row) {
      if (!row.contractEffectEndDate && !row.contractEffectStartDate) {
        return '/';
      }
      return '-';
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      if (this.curTabName === 'all') {
        this.fetchData();
      }
    },
    queryClick() {
      if (this.isOtherTab) {
        for (const key of Object.keys(this.otherFilterInput)) {
          if (!this.otherFilterInput[key] && this.otherFilterInput[key] !== 0) {
            delete this.otherFilterInput[key];
          }
        }
        if (JSON.stringify(this.otherFilterInput) === '{}') {
          this.otherList = [];
          return;
        }
      }
      this.fetchData(true);
    },
    queryEmpty() {
      this.sortType = '';
      this.sortName = '';
      if (this.isOtherTab) {
        this.otherFilterInput = {};
      } else {
        this.filterInput = {};
      }
      this.queryClick();
    },
    handleSizeChange(val) {
      if (this.curTabName === 'all') {
        this.perPage = val;
        this.fetchData(true);
      }
    },
    handleCurrentChange(toPage) {
      if (this.curTabName === 'all') {
        this.page = toPage;
        this.fetchData();
      }
    },
    // 获取列表数据
    fetchData(reset = false) {
      try {
        if (reset) this.page = 1;
        this.listLoading = true;
        const params = JSON.parse(JSON.stringify(this.paramsObj));
        params.page = this.isOtherTab ? 1 : this.page;
        params.perPage = this.isOtherTab ? 10 : this.perPage;
        if (!this.isOtherTab) {
          params.sortName = this.sortName;
          params.sortType = this.sortType;
        }

        params.handleStatus = -1;
        params.excludeProcess = 0; // 固定参数,过滤草稿状态的合同
        params.isOther = this.isOtherTab;
        paramsRangeFormat(this.rangeKeyArr, params);
        paramsAryToStr(['departmentIdList'], params);
        params.hasContractCode = true; // 只筛选已经生成合同编码的合同
        if (this.cancelToken) this.cancelToken.cancel('cancel');
        const source = axios.CancelToken.source();
        this.cancelToken = source;
        if (this.expandParams) {
          Object.keys(this.expandParams).forEach(key => {
            if (key !== 'oppCompanyType' || (key === 'oppCompanyType' && params.oppCompanyId)) {
              params[key] = this.expandParams[key];
            }
          });
        }
        getList(params, source.token).then(({ data }) => {
          if (this.isOtherTab) { this.otherList = data.items; } else { this.list = data; }
          this.listLoading = false;
          this.listLoading = false;
        }).catch(e => {
          console.error(e);
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 切换列表tab
    onSubActiveOrderChange(data) {
      if (data.paneName === 'all') {
        this.fetchData();
      } else if (data.paneName === 'other') {
        if (this.cancelToken) this.cancelToken.cancel('cancel');
      }
    },
    // 跳转合同详情
    toDetail(row) {
      const routeUrl = this.$router.resolve({
        name: 'contractDetail',
        params: { id: encryption(row.id) },
        query: {
          processId: encryption(row.processId)
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-tabs__header {
  margin: 0;
  border: none;
}
::v-deep .el-badge__content{
  background: #FB5227;
}
::v-deep .el-badge__content{
  transform: translateY(5px);
}
.tip {
  color: #999;
  font-size: 13px;
  margin-left: 20px;;
}
.drawer-content {
  overflow-y: auto;
  .table-list {
    &::v-deep {
     .el-table__header {
        .el-checkbox__inner {
          position: relative;
          left: -2px;
        }
      }
    }
    border-radius: 10px;
    .el-row {
      padding: 0;
    }
    .delete-button-container {
      flex:1;
      height: 32px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    ::v-deep .pagination-flex {
      position: absolute;
      width: 100% !important;
    }
  }
}
::v-deep .el-tabs__nav-wrap::after {
  z-index: -1;
}
::v-deep .el-tabs__active-bar {
  bottom: 1px;
}
.contract-detail-tabs-container {
  &::v-deep {
    .el-tabs__header  {
      margin-bottom: 0 !important;
      border-bottom: 1px solid #ddd;
      .el-tabs__nav {
        border: none !important;
        height: 32px !important;
      }
      .el-tabs__item {
        padding: 0 12px !important;
        height: 32px !important;
        line-height: 32px !important;
        margin-right: 8px;
        border: 1px solid #ddd;
        border-radius: 4px 4px 0px 0px;
        color: #333;
        background: #f7f8fa;
        font-size: 16px;
        &:last-child {
          margin-right: 0px;
        }
        &.is-active {
          border-bottom-color: #FFFFFF !important;
          font-weight: bold;
          background: #fff;
          color: #406eff;
        }
      }
    }
  }
}
</style>
